package com.mzpai.product.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gexin.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mzpai.product.constant.OrderConstants;
import com.mzpai.product.constant.OrderStatusConstants;
import com.mzpai.product.constant.PayConstants;
import com.mzpai.product.exception.ProductResException;
import com.mzpai.product.exception.ProductResExceptionCode;
import com.mzpai.product.mapper.StoreOrderMapper;
import com.mzpai.product.model.StoreCart;
import com.mzpai.product.model.StoreOrder;
import com.mzpai.product.model.StoreOrderCartInfo;
import com.mzpai.product.model.StoreOrderStatus;
import com.mzpai.product.model.StoreProduct;
import com.mzpai.product.model.StoreProductAttrValue;
import com.mzpai.product.model.StoreReminder;
import com.mzpai.product.model.SystemStore;
import com.mzpai.product.model.SystemStoreBill;
import com.mzpai.product.model.SystemStoreDdfBill;
import com.mzpai.product.model.SystemStoreDdfTrade;
import com.mzpai.product.model.User;
import com.mzpai.product.model.WstPayments;
import com.mzpai.product.service.StoreCartService;
import com.mzpai.product.service.StoreDdfBillService;
import com.mzpai.product.service.StoreOrderCartInfoService;
import com.mzpai.product.service.StoreOrderService;
import com.mzpai.product.service.StoreOrderStatusService;
import com.mzpai.product.service.StoreProductAttrValueService;
import com.mzpai.product.service.StoreProductService;
import com.mzpai.product.service.StoreReminderService;
import com.mzpai.product.service.SystemStoreBillService;
import com.mzpai.product.service.SystemStoreDdfTradeService;
import com.mzpai.product.service.SystemStoreService;
import com.mzpai.product.service.UserService;
import com.mzpai.product.util.StoreOrderCashierAccountHandler;
import com.mzpai.product.vo.StoreCashierAccountReqVo;
import com.mzpai.product.vo.StoreCashierProductVo;
import com.mzpai.product.vo.StoreCashierSucessVo;
import com.mzpai.product.vo.StoreOfflinePayOrderVo;
import com.mzpai.product.vo.StoreOnlinePayOrderVo;
import com.mzpai.product.vo.StoreOrderVo;
import com.mzpai.service.impl.BaseServiceImpl;
import com.mzpai.util.ArithUtil;
import com.mzpai.util.DateUtil;
import com.mzpai.util.PageUtil;
import com.mzpai.util.StringUtils;
import com.mzpai.vo.ResponseVo;
/**
 *
 * <b>订单列表 | Service</b><br>
 *
 * yanglijun 2021-04-09 23:51:49
 * 
 *  @version 1.0.0
 *
 */
@Service
public class StoreOrderServiceImpl extends BaseServiceImpl<StoreOrder> implements StoreOrderService {

	Logger logger = LoggerFactory.getLogger(StoreOrder.class);

	@Autowired 
	private StoreOrderMapper storeOrderMapper;
	
	@Autowired
	private StoreCartService storeCartService;
	
	@Autowired
	private StoreOrderCartInfoService storeOrderCartInfoService;
	
	@Autowired
	private StoreDdfBillService storeDdfBillService;
	
	@Autowired
	private StoreProductService storeProductService;
	
	@Autowired
	private SystemStoreDdfTradeService systemStoreDdfTradeService;
	
	@Autowired
	private StoreOrderStatusService storeOrderStatusService;
	
	@Autowired
	private StoreProductAttrValueService StoreProductAttrValueService;
	@Autowired 
	private SystemStoreBillService systemStoreBillService;
	@Autowired 
	private SystemStoreService systemStoreService;
	@Autowired
	private StoreReminderService storeReminderService;
	
	@Autowired 
	private UserService userService;

	/***
	 * 返回vo 
	 * @param map
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageInfo<StoreOrderVo> getVoListPage(Map<String, Object> map, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		return PageUtil.toPageInfo(storeOrderMapper.getVoListPage(map));
	}

	/**
	 * 1.新增购物车(eb_store_cart)
	 * 2.新增订单信息(eb_store_order)
	 * 3.新增订单购物详情表(eb_store_order_cart_info)
	 * 4.单单反抵扣金明细(eb_system_store_ddf_bill)
	 * 5.单单反抵扣金交易明细(eb_system_store_ddf_trade)
	 * 6.新增订单操作记录表(eb_store_order_status)
	 */
	@Override
	public StoreOfflinePayOrderVo createStoreOfflinePayOrder(StoreCashierAccountReqVo cshierAccountReqVo,User user,WstPayments wstPayments,String defaultOrderType) {
		
		//全局信息
		Integer storeId = cshierAccountReqVo.getStoreId();
		Integer userId=user.getUid();
		
		BigDecimal deducteGold = cshierAccountReqVo.getDeducteGold();//要使用抵扣金
		BigDecimal discountAmount = cshierAccountReqVo.getDiscountAmount();//优惠金额
		if(deducteGold==null){
			deducteGold=new BigDecimal(0);
		}
		
        if(discountAmount==null){
        	discountAmount=new BigDecimal(0);
		}

        
      //校验要使用抵扣金是否充足
  		BigDecimal balanceTotal=getTotalDeducteGold(storeId,userId);
  		Double balanceDeducteGold=balanceTotal.doubleValue();
  		
  		
  		if(deducteGold.doubleValue()>balanceDeducteGold){
  			//抵扣金不够
  			throw new ProductResException(ProductResExceptionCode.DEDUCT_NOTHING_USE.getCode(),ProductResExceptionCode.DEDUCT_NOTHING_USE.getMessage());
  		}
      		
		
		Integer totalNum = cshierAccountReqVo.getTotalNum();//订单商品总数
		BigDecimal totalPrice = cshierAccountReqVo.getTotalPrice();//订单总金额
		
		List<StoreCashierProductVo> productList = cshierAccountReqVo.getProductList();//商品详情
		
		/**
		 * 1.新增购物车
		 */
		List<StoreCart> storeCartAddList = addStoreCart(productList, storeId, userId);
		
		
		/**
		 * 2.新增订单
		 *   a.获取购物车id
		 *   b.构造订单信息
		 */
		List<Integer> cartIdList = StoreOrderCashierAccountHandler.getCartIdList(storeCartAddList);
		String cartId=null;
		if(cartIdList!=null && !cartIdList.isEmpty()){
			cartId=cartIdList.toString();
		}
		StoreOrder storeOrder = createPayOrderrModel(storeId,user, wstPayments,deducteGold,discountAmount);
		//支付状态 
		storeOrder.setPaid(PayConstants.PAY_STATE_1);
		//订单状态（-1 : 申请退款 -2 : 退货成功 0：待发货；1：待收货；2：已收货；3：待评价；-1：已退款）
		storeOrder.setStatus(OrderStatusConstants.ORDER_STATUS_2);
		
		if(!StringUtils.isNullOrBlank(defaultOrderType)){
			storeOrder.setOrderType(defaultOrderType);//设置默认访客订单类型
		}else{
			storeOrder.setOrderType(OrderConstants.ORDER_TYPE_2);
		}
		
		//设置订单基本信息
		storeOrder.setTotalNum(totalNum);
		storeOrder.setTotalPrice(totalPrice);
		storeOrder.setCartId(cartId);
		
		//实际支付金额
		//运费金额    目前看下单设置的为零 确认下设置值？？
		BigDecimal freightPrice=new BigDecimal(0);
		storeOrder.setFreightPrice(freightPrice);
		//邮费   确认下获取值逻辑设置值？？
		BigDecimal totalPostage=new BigDecimal(0);
		storeOrder.setTotalPostage(totalPostage);
		//邮费   确认下获取值逻辑设置值？？
		BigDecimal payPostage=new BigDecimal(0);
		storeOrder.setPayPostage(payPostage);
		Double payPrice=(totalPrice.doubleValue()+totalPostage.doubleValue()+freightPrice.doubleValue())-deducteGold.doubleValue()-discountAmount.doubleValue();
		//防止实际支付 负数
		if(payPrice<0){
			payPrice=0d;
		}
		storeOrder.setPayPrice(new BigDecimal(payPrice));  
		
		/**
		 * 计算使用或获得抵扣金
		 * 1.先判断是否拥有有效抵扣金(eb_system_store_ddf_bill)
		 *    a.如果存在:则使用抵扣金进行扣除,即使当前商品存在有效单单返规则也不再生成新的抵扣金返回,本订单获取抵扣金为零(下次再下单再返回)
		 *    b.如果不存在: 查询抵扣金配置表,如果配置表存在有效期内抵扣金规则且有商品参与抵扣金则此单返回抵扣金,同时设置获得抵扣金额(一期先不做返回逻辑)
		 * 2.本单是否单单返订单
		 *    确认逻辑:如果此订单使用了抵扣金或者此单有返回抵扣金均为单单返单;否则不是  
		 */
		Map<String,Object> ddfBillMap=new HashMap<String,Object>();
		ddfBillMap.put("storeId", storeId);
		ddfBillMap.put("userId", userId);
		List<SystemStoreDdfBill> storeDdfBillList=storeDdfBillService.getEffectiveStoreDdfBillList(ddfBillMap);
		if(storeDdfBillList!=null && !storeDdfBillList.isEmpty()){
			BigDecimal getDdfPrice=new BigDecimal(0);
			storeOrder.setGetDdfPrice(getDdfPrice);
			storeOrder.setIsDdf(1);
		}else{
			//二期 考虑实现上面b如果不存在逻辑
			BigDecimal ddfPrice=new BigDecimal(0);
			storeOrder.setGetDdfPrice(ddfPrice);
			storeOrder.setIsDdf(0);//是否单单返订单 0:否;1:是
		}
		storeOrderMapper.insert(storeOrder);
		Integer orderprimaryId=storeOrder.getId();
		
		/**
		 * 新增订单购物详情表(eb_store_order_cart_info)
		 */
		if(storeCartAddList!=null && !storeCartAddList.isEmpty()){
			List<StoreOrderCartInfo> storeOrderCartInfoList = setStoreOrderCartInfo(storeId, totalPrice,storeCartAddList,orderprimaryId);
			storeOrderCartInfoService.insertBatch(storeOrderCartInfoList);
		}
		//构造 cartInfo json信息
		
		/**添加门店动态*/
		this.saveStoreReminder(storeOrder);
		
		
		/**
		 * 单单反抵扣金明细
		 * 
		 */
		if(storeDdfBillList!=null && !storeDdfBillList.isEmpty()){
			
			Double currentUseTotalValue=0.00d;
			Double orderUse=deducteGold.doubleValue();
			
			for(SystemStoreDdfBill storeDdfBill:storeDdfBillList){
				Long billId=storeDdfBill.getId();
				String ddfBillOrderId=storeDdfBill.getOrderId();
				BigDecimal totalAmount=storeDdfBill.getTotalAmount();//发放总金额
				BigDecimal usedAmount=storeDdfBill.getUsedAmount();//已使用总金额
				BigDecimal balance=storeDdfBill.getBalance();//余额
				
				
				Integer currentDateTime=(int) (new Date().getTime()/1000);
					//前端传递 要是有抵扣金额 deducteGold
					Double balanceValue=balance.doubleValue();
					currentUseTotalValue=ArithUtil.add(currentUseTotalValue, balanceValue);
					//要是用大于余额则全部使用
					if(currentUseTotalValue<=orderUse){
						//根据id更新对应已使用额度和剩余总额
						SystemStoreDdfBill updateStoreDdfBill=new SystemStoreDdfBill();
						updateStoreDdfBill.setId(billId);
						updateStoreDdfBill.setUsedAmount(totalAmount);
						BigDecimal upbalance=new BigDecimal(0);
						updateStoreDdfBill.setBalance(upbalance);
						storeDdfBillService.update(updateStoreDdfBill);
						
						//记录单单反抵扣金交易明细(eb_system_store_ddf_trade)
						SystemStoreDdfTrade systemStoreDdfTrade=new SystemStoreDdfTrade();
						systemStoreDdfTrade.setStoreId(storeId);
						systemStoreDdfTrade.setUid(userId);
						systemStoreDdfTrade.setBillId(billId);
						systemStoreDdfTrade.setOrderId(ddfBillOrderId);
						systemStoreDdfTrade.setType((byte)2);
						BigDecimal number=new BigDecimal(balanceValue);//使用掉余额
						systemStoreDdfTrade.setNumber(number);
						systemStoreDdfTrade.setAddTime(currentDateTime);
						systemStoreDdfTradeService.save(systemStoreDdfTrade);
						orderUse=orderUse-currentUseTotalValue;
					}else{
						//根据id更新对应已使用额度和剩余总额
						SystemStoreDdfBill updateStoreDdfBill=new SystemStoreDdfBill();
						updateStoreDdfBill.setId(billId);
						
						BigDecimal upUseAmount=new BigDecimal(orderUse+usedAmount.doubleValue());
						updateStoreDdfBill.setUsedAmount(upUseAmount);
						
						BigDecimal upbalance=new BigDecimal(totalAmount.doubleValue()-upUseAmount.doubleValue());
						updateStoreDdfBill.setBalance(upbalance);
						storeDdfBillService.update(updateStoreDdfBill);
						
						//记录单单反抵扣金交易明细(eb_system_store_ddf_trade)
						SystemStoreDdfTrade systemStoreDdfTrade=new SystemStoreDdfTrade();
						systemStoreDdfTrade.setStoreId(storeId);
						systemStoreDdfTrade.setUid(userId);
						systemStoreDdfTrade.setBillId(billId);
						systemStoreDdfTrade.setOrderId(ddfBillOrderId);
						systemStoreDdfTrade.setType((byte)2);
						BigDecimal number=new BigDecimal(orderUse);
						systemStoreDdfTrade.setNumber(number);
						systemStoreDdfTrade.setAddTime(currentDateTime);
						systemStoreDdfTradeService.save(systemStoreDdfTrade);
						break;
					}
			}
		}
				
		/**
		 * 新增订单操作记录表
		 */
		List<StoreOrderStatus> orderStatusList=new ArrayList<StoreOrderStatus>();
		Integer currentTime=(int) (new Date().getTime()/1000);
		StoreOrderStatus createStoreOrderStatus=new StoreOrderStatus();
		createStoreOrderStatus.setOid(orderprimaryId);
		createStoreOrderStatus.setChangeType("cache_key_create_order");
		createStoreOrderStatus.setChangeMessage("订单生成");
		createStoreOrderStatus.setChangeTime(currentTime);
		
		StoreOrderStatus payStoreOrderStatus=new StoreOrderStatus();
		payStoreOrderStatus.setOid(orderprimaryId);
		payStoreOrderStatus.setChangeType("pay_success");
		payStoreOrderStatus.setChangeMessage("用户付款成功");
		payStoreOrderStatus.setChangeTime(currentTime);
		orderStatusList.add(createStoreOrderStatus);
		orderStatusList.add(payStoreOrderStatus);
		storeOrderStatusService.insertBatch(orderStatusList);
		
		
		StoreOfflinePayOrderVo storeOfflinePayOrderVo=new StoreOfflinePayOrderVo();
		storeOfflinePayOrderVo.setOrderId(storeOrder.getOrderId());
		storeOfflinePayOrderVo.setPayPrice(storeOrder.getPayPrice());
		return storeOfflinePayOrderVo;
	}

	private List<StoreOrderCartInfo> setStoreOrderCartInfo(Integer storeId, BigDecimal totalPrice,List<StoreCart> storeCartAddList,
			Integer orderprimaryId) {
		List<StoreOrderCartInfo> storeOrderCartInfoList=new ArrayList<StoreOrderCartInfo>();
		for(StoreCart storeCart:storeCartAddList){
			
			Integer storeCartId=storeCart.getId();
			Integer productId=storeCart.getProductId();
			Integer attrValueId=storeCart.getAttrValueId();
			
			String productAttrUnique=storeCart.getProductAttrUnique();
			Integer cartNum=storeCart.getCartNum();
			Integer combinationId=storeCart.getCombinationId();
			Integer seckillId=storeCart.getSeckillId();
			Integer bargainId=storeCart.getBargainId();
			
			StoreProduct storeProduct=storeProductService.queryByPrimaryId(productId);
			Integer factoryId=storeProduct.getFactoryId();
			Integer factoryPid=storeProduct.getFactoryPid();
			String productImage=storeProduct.getImage();
			BigDecimal productPrice=storeProduct.getPrice();
			Double productPriceValue=productPrice.doubleValue();
			BigDecimal productOtPrice=storeProduct.getOtPrice();
			Double productOtPriceValue=productOtPrice.doubleValue();
			BigDecimal productVipPrice=storeProduct.getVipPrice();
			Double productVipPriceValue=productVipPrice.doubleValue();
			BigDecimal productPostage=storeProduct.getPostage();
			Double productPostageValue=productPostage.doubleValue();
			BigDecimal productGiveIntegral=storeProduct.getGiveIntegral();
			Double productGiveIntegralValue=productGiveIntegral.doubleValue();
			
			Integer productSales=storeProduct.getSales();
			Integer productStock=storeProduct.getStock();
			String productStoreName=storeProduct.getStoreName();
			String nuitName=storeProduct.getUnitName();
			Integer isPostage=storeProduct.getIsPostage();
			BigDecimal productCost=storeProduct.getCost();
			Double productCostValue=productCost.doubleValue();
			Integer isSub=storeProduct.getIsSub();
			Integer tempId=storeProduct.getTempId();
			
			
			StoreOrderCartInfo storeOrderCartInfo=new StoreOrderCartInfo();
			storeOrderCartInfo.setOid(orderprimaryId);
			storeOrderCartInfo.setCartId(storeCartId);
			storeOrderCartInfo.setProductId(productId);
			//购买东西的详细信息 待拼接 json串 TO DO  待处理待处理
			/**
			 * 设置 cartInfo信息 start
			 */
			JSONObject cartInfo = new JSONObject();
			//eb_store_cart 表信息
			cartInfo.put("id", storeCartId);
			cartInfo.put("type", "product");
			cartInfo.put("product_id", productId);
			cartInfo.put("product_attr_unique", productAttrUnique);
			cartInfo.put("cart_num", cartNum);
			cartInfo.put("combination_id", combinationId);
			cartInfo.put("seckill_id", seckillId);
			cartInfo.put("bargain_id", bargainId);
			cartInfo.put("store_id", storeId);
			
			//设置 productInfo
			Map<String, Object> productInfomap = new HashMap<String, Object>();
			
			//商品表eb_store_product上字段
			productInfomap.put("id", productId);
			productInfomap.put("image", productImage);
			productInfomap.put("price", String.valueOf(productPriceValue));
			productInfomap.put("ot_price", String.valueOf(productOtPriceValue));
			productInfomap.put("vip_price", String.valueOf(productVipPriceValue));
			productInfomap.put("postage", String.valueOf(productPostageValue));
			productInfomap.put("give_integral", String.valueOf(productGiveIntegralValue));
			productInfomap.put("sales", productSales);
			productInfomap.put("stock", productStock);
			productInfomap.put("store_name", productStoreName);
			productInfomap.put("unit_name", nuitName);
			productInfomap.put("is_postage", isPostage);
			productInfomap.put("cost", String.valueOf(productCostValue));
			productInfomap.put("store_id", storeId);
			productInfomap.put("factory_pid", factoryPid);
			productInfomap.put("is_sub", isSub);
			productInfomap.put("temp_id", tempId);
			//确认下此字段值 todo
			productInfomap.put("supplier_cost", null);
			
			
			//设置attrInfo
			StoreProductAttrValue storeProductAttrValue=StoreProductAttrValueService.queryByPrimaryId(attrValueId);
			String attrValueSuk=storeProductAttrValue.getSuk();
			Integer attrValueStock=storeProductAttrValue.getStock();
			Integer attrValueSales=storeProductAttrValue.getSales();
			BigDecimal attrValuePrice=storeProductAttrValue.getPrice();
			Double attrValuePriceValue=attrValuePrice.doubleValue();
			String attrValueImage=storeProductAttrValue.getImage();
			String attrValueUnique=storeProductAttrValue.getUnique();
			BigDecimal attrValueCost=storeProductAttrValue.getCost();
			Double attrValueCostValue=attrValueCost.doubleValue();
			BigDecimal attrValueMinPrice=storeProductAttrValue.getMinPrice();
			Double attrValueMinPriceValue=attrValueMinPrice.doubleValue();
			String attrValueBarCode=storeProductAttrValue.getBarCode();
			BigDecimal attrValueOtPrice=storeProductAttrValue.getOtPrice();
			Double attrValueOtPriceValue=attrValueOtPrice.doubleValue();
			BigDecimal attrValueWeight=storeProductAttrValue.getWeight();
			Double attrValueWeightValue=attrValueWeight.doubleValue();
			BigDecimal attrValueVolume=storeProductAttrValue.getVolume();
			Double attrValueVolumeValue=attrValueVolume.doubleValue();
			BigDecimal attrValueBrokerage=storeProductAttrValue.getBrokerage();
			Double attrValueBrokerageValue= attrValueBrokerage.doubleValue();
			BigDecimal attrValueBrokerageTwo=storeProductAttrValue.getBrokerageTwo();
			Double attrValueBrokerageTwoValue=attrValueBrokerageTwo.doubleValue();
			Integer attrValueType=storeProductAttrValue.getType();
			Integer attrValueQuota=storeProductAttrValue.getQuota();
			Integer attrValueQuotaShow=storeProductAttrValue.getQuotaShow();
			Integer attrValueState=storeProductAttrValue.getState();
			
			Map<String, Object> attrInfomap = new HashMap<String, Object>();
//			String sukUniCode=StringUtils.getUnicode(attrValueSuk);
			
			attrInfomap.put("product_id", productId);
			attrInfomap.put("suk", attrValueSuk);
			attrInfomap.put("stock", attrValueStock);
			attrInfomap.put("sales", attrValueSales);
			attrInfomap.put("price", String.valueOf(attrValuePriceValue));
			attrInfomap.put("image", attrValueImage);
			attrInfomap.put("unique", attrValueUnique);
			attrInfomap.put("cost", String.valueOf(attrValueCostValue));
			attrInfomap.put("min_price", String.valueOf(attrValueMinPriceValue));
			attrInfomap.put("bar_code", attrValueBarCode);
			attrInfomap.put("ot_price", String.valueOf(attrValueOtPriceValue));
			attrInfomap.put("weight", String.valueOf(attrValueWeightValue));
			attrInfomap.put("volume", String.valueOf(attrValueVolumeValue));
			attrInfomap.put("brokerage", String.valueOf(attrValueBrokerageValue));
			attrInfomap.put("brokerage_two", String.valueOf(attrValueBrokerageTwoValue));
			attrInfomap.put("type", attrValueType);
			attrInfomap.put("quota", attrValueQuota);
			attrInfomap.put("quota_show", attrValueQuotaShow);
			attrInfomap.put("state", attrValueState);
			attrInfomap.put("store_id", storeId);
			
			productInfomap.put("attrInfo", attrInfomap);
			cartInfo.put("productInfo", productInfomap);
			
			//如下5个字段待确定哪个表里哪个字段 TO DO...........
			//订单优惠和抵扣前 总金额
			cartInfo.put("truePrice", totalPrice.doubleValue());
			cartInfo.put("vip_truePrice", productVipPriceValue);
			cartInfo.put("trueStock", attrValueStock);
			cartInfo.put("costPrice", String.valueOf(attrValueCostValue));
			cartInfo.put("sCostPrice", 0);
			
			/**
			 * 设置 cartInfo信息 end
			 */
			String cartJsonStr=cartInfo.toJSONString();
			String cartJsonStrUniCode=StringUtils.getUnicode(cartJsonStr);
			storeOrderCartInfo.setCartInfo(cartJsonStrUniCode);
			storeOrderCartInfo.setUnique(productAttrUnique);
			storeOrderCartInfo.setFactoryId(factoryId);
			storeOrderCartInfoList.add(storeOrderCartInfo);
		}
		return storeOrderCartInfoList;
	}

	/**
	 * 新增购物车数据
	 * @param productList 商品详情
	 * @param storeId  门店id
	 * @param userId  用户id
	 * @return List<StoreCart> 返回新增后购物车信息,包含主键id
	 */
	private List<StoreCart> addStoreCart(List<StoreCashierProductVo> productList, Integer storeId, Integer userId) {
		List<StoreCart> storeCartAddList=null;
		if(productList!=null && !productList.isEmpty()){
			List<StoreCart> storeCartList=new ArrayList<StoreCart>();
			for(StoreCashierProductVo productVo:productList){
				StoreCart storeCart = setStoreCart(storeId, userId, productVo);
				storeCartList.add(storeCart);
			}
			storeCartAddList=storeCartService.insertBatch(storeCartList);
		}
		return storeCartAddList;
	}

	/**
	 * 设置订单基本信息
	 * @param storeId
	 * @param deducteGold  要使用抵扣金
	 * @param discountAmount 优惠金额
	 * @return StoreOrder
	 */
	private StoreOrder createPayOrderrModel(Integer storeId,User user, WstPayments wstPayments,BigDecimal deducteGold, BigDecimal discountAmount) {
		
		/**
		 * 基本参数
		 */
		Integer userId=user.getUid();
		String realName=user.getRealName();
		String userPhone=user.getPhone();
		String userAddress=user.getAddres();
		String orderId=OrderConstants.CASHIERORDER_BEGIN+DateUtil.getDateFormateDate()+StringUtils.randomString(6,true);
		Integer dateTime=(int) (new Date().getTime()/1000);
		String payCode=wstPayments.getPayCode();
		String payType=wstPayments.getPayName();
		
		/**
		 * 设置订单信息
		 * 
		 */
		StoreOrder storeOrder=new StoreOrder();
		storeOrder.setStoreId(storeId);
		storeOrder.setOrderId(orderId);		
		storeOrder.setUid(userId);
		if(StringUtils.isNullOrBlank(realName)){
			storeOrder.setRealName("");
		}else{
			storeOrder.setRealName(realName);
		}
		
		if(StringUtils.isNullOrBlank(userPhone)){
			storeOrder.setUserPhone("");
		}else{
			storeOrder.setUserPhone(userPhone);
		}
		
		if(StringUtils.isNullOrBlank(userAddress)){
			storeOrder.setUserAddress("");
		}else{
			storeOrder.setUserAddress("");
		}
		
		storeOrder.setDiscountAmount(discountAmount);
		storeOrder.setPayTime(dateTime);
		storeOrder.setPayType(payType);
		storeOrder.setAddTime(dateTime);
		storeOrder.setPayCode(payCode);
		//退款图片
		storeOrder.setRefundReasonWapImg(null);
		//退款用户说明
		storeOrder.setRefundReasonWapExplain(null);
		//退款时间
		storeOrder.setRefundReasonTime(null);
		//前台退款原因
		storeOrder.setRefundReasonWap(null);
		//不退款的理由
		storeOrder.setRefundReason(null);
		//快递名称/送货人姓名  
		storeOrder.setDeliveryName(null);
		//发货类型
		storeOrder.setDeliveryType(null);
		//快递单号/手机号
		storeOrder.setDeliveryId(null);
		
		//设置抵扣金额  目前看设置的为零？？
		BigDecimal deductionPrice=new BigDecimal(0d);
		storeOrder.setDeductionPrice(deductionPrice);
		
		//优惠券id 确认下目前是否有优惠券逻辑	
		Integer couponId=0;	
		storeOrder.setCouponId(couponId);
		//优惠券金额  目前看设置的为零？？
		BigDecimal couponPrice=new BigDecimal(0d);
		storeOrder.setCouponPrice(couponPrice);
		
		//0 未退款 1 申请中 2 已退款
		Integer refundStatus=0;
		storeOrder.setRefundStatus(refundStatus);
		//退款金额
		BigDecimal refundPrice=new BigDecimal(0d);
		storeOrder.setRefundPrice(refundPrice);
		//消费赚取积分
		BigDecimal gainIntegral=new BigDecimal(0d);
		storeOrder.setGainIntegral(gainIntegral);
		//使用积分
		BigDecimal useIntegral=new BigDecimal(0d);
		storeOrder.setUseIntegral(useIntegral);
		//给用户退了多少积分
		BigDecimal backIntegral=new BigDecimal(0d);
		storeOrder.setBackIntegral(backIntegral);
		//备注
		String mark="";
		storeOrder.setMark(mark);
		//是否删除
		Integer idDel=0;
		storeOrder.setIsDel(idDel); 
		//唯一id(md5加密)类似id
		storeOrder.setUnique(StringUtils.uuid());
		//管理员备注
		storeOrder.setRemark(null);
		//商户ID 目前看数据都为0 确认逻辑？？
		storeOrder.setMerId(0);
		storeOrder.setIsMerCheck(0);
		//拼团商品id0一般商品
		storeOrder.setCombinationId(0);
		//拼团id 0没有拼团
		storeOrder.setPinkId(0);
		//成本价
		BigDecimal cost=new BigDecimal(0d);
		storeOrder.setCost(cost);
		//秒杀商品ID
		storeOrder.setSeckillId(0);
		//砍价id
		storeOrder.setBargainId(0);
		//核销码 确认生成方式 或来源 ???  
		String verifyCode="";
		storeOrder.setVerifyCode(verifyCode);
		//配送方式 1=快递 ，2=门店自提 产品确认逻辑如果线下付款了 是否存在配送方式问题？？
		Integer shippingType=2;
		storeOrder.setShippingType(shippingType);
		//店员id 目前设置的都是零
		storeOrder.setClerkId(0);
		//消息提醒 待定 怎么确定值？？
		Integer isRemind=0;
		storeOrder.setIsRemind(isRemind);
		storeOrder.setIsSystemDel(0);
		//使用的单单返金额
		storeOrder.setUsedDdfPrice(deducteGold);
		return storeOrder;
	}

	
	/**
	 * 设置购物车信息
	 * @param storeId
	 * @param userId
	 * @param productVo
	 * @return
	 */
	private StoreCart setStoreCart(Integer storeId, Integer userId, StoreCashierProductVo productVo) {
		Integer productId = productVo.getId();
		Integer attrValueId = productVo.getAttrValueId();
		String attrValueUnique = productVo.getAttrValueUnique();
		Integer cartNum = productVo.getNumber();
		
		StoreCart storeCart=new StoreCart();
		storeCart.setUid(userId);
		storeCart.setType("product");
		//购物车商品来源 1:小程序;2:甄赚钱收银APP
		storeCart.setSource("2");
		storeCart.setProductId(productId);
		storeCart.setProductAttrUnique(attrValueUnique);
		storeCart.setCartNum(cartNum);
		Date date=DateUtil.getDateNow();
		Integer addTime=(int) (date.getTime()/1000);
		storeCart.setAddTime(addTime);
		storeCart.setIsPay(1);
		storeCart.setIsDel(0);
		storeCart.setIsNew(0);
		storeCart.setCombinationId(0);
		storeCart.setSeckillId(0);
		storeCart.setBargainId(0);
		storeCart.setStoreId(storeId);
		storeCart.setAttrValueId(attrValueId);
		return storeCart;
	}
	
	private BigDecimal getTotalDeducteGold(Integer storeId, Integer userId) {
		BigDecimal balanceTotal=null;
		//查询用户在门店下可以抵扣金总额
		Map<String,Object> ddfBillMap=new HashMap<String,Object>();
		ddfBillMap.put("storeId", storeId);
		ddfBillMap.put("userId", userId);
		List<SystemStoreDdfBill> storeDdfBillList=storeDdfBillService.getEffectiveStoreDdfBillList(ddfBillMap);
		if(storeDdfBillList!=null && !storeDdfBillList.isEmpty()){
			double blaceTotalValue=0.00d;
			for(SystemStoreDdfBill storeDdfBill:storeDdfBillList){
				//发放总金额
				BigDecimal totalAmount=storeDdfBill.getTotalAmount();
				//已使用总金额
				BigDecimal usedAmount=storeDdfBill.getUsedAmount();
				//余额
				BigDecimal balance=storeDdfBill.getBalance();
				//防止 使用总额大于发放总额
				if(totalAmount.doubleValue()>usedAmount.doubleValue()){
					Double balanceValue=balance.doubleValue();
					blaceTotalValue=ArithUtil.add(blaceTotalValue,balanceValue);
				}
			}
			balanceTotal=new BigDecimal(blaceTotalValue);
		}else{
			balanceTotal=new BigDecimal(0);
		}
		return balanceTotal;
	}

	@Override
	public StoreOnlinePayOrderVo createStoreOnlinePayOrder(StoreCashierAccountReqVo cshierAccountReqVo,User user,WstPayments wstPayments,String defaultOrderType) {
		
		//全局信息
		Integer storeId = cshierAccountReqVo.getStoreId();
		Integer userId=user.getUid();
		BigDecimal deducteGold = cshierAccountReqVo.getDeducteGold();//要使用抵扣金
		BigDecimal discountAmount = cshierAccountReqVo.getDiscountAmount();//优惠金额
		Integer totalNum = cshierAccountReqVo.getTotalNum();//订单商品总数
		BigDecimal totalPrice = cshierAccountReqVo.getTotalPrice();//订单总金额
		List<StoreCashierProductVo> productList = cshierAccountReqVo.getProductList();//商品详情
		
		//校验要使用抵扣金是否充足
		BigDecimal balanceTotal=getTotalDeducteGold(storeId,userId);
		Double balanceDeducteGold=balanceTotal.doubleValue();
		
		if(deducteGold==null){
			deducteGold=new BigDecimal(0);
		}
		
        if(discountAmount==null){
        	discountAmount=new BigDecimal(0);
		}
		
		if(deducteGold.doubleValue()>balanceDeducteGold){
			//抵扣金不够
			throw new ProductResException(ProductResExceptionCode.DEDUCT_NOTHING_USE.getCode(),ProductResExceptionCode.DEDUCT_NOTHING_USE.getMessage());
		}
		
		/**
		 * 1.新增购物车
		 */
		List<StoreCart> storeCartAddList = addStoreCart(productList, storeId, userId);
		
		/**
		 * 2.新增订单
		 *   a.获取购物车id
		 *   b.构造订单信息
		 */
		List<Integer> cartIdList = StoreOrderCashierAccountHandler.getCartIdList(storeCartAddList);
		String cartId=null;
		if(cartIdList!=null && !cartIdList.isEmpty()){
			cartId=cartIdList.toString();
		}
		StoreOrder storeOrder = createPayOrderrModel(storeId,user, wstPayments,deducteGold,discountAmount);
		//支付状态 
		storeOrder.setPaid(PayConstants.PAY_STATE_0);
		//订单状态（-1 : 申请退款 -2 : 退货成功 0：待发货；1：待收货；2：已收货；3：待评价；-1：已退款）
		storeOrder.setStatus(OrderStatusConstants.ORDER_STATUS_0);
		
		if(!StringUtils.isNullOrBlank(defaultOrderType)){
			storeOrder.setOrderType(defaultOrderType);
		}else{
			storeOrder.setOrderType(OrderConstants.ORDER_TYPE_2);
		}
		storeOrder.setIsChannel(PayConstants.IS_CHANNEL_3);//支付渠道 0:微信公众号;1:微信小程序;2:到店付款;3:在线付款
				
		//设置订单基本信息
		storeOrder.setTotalNum(totalNum);
		storeOrder.setTotalPrice(totalPrice);
		storeOrder.setCartId(cartId);
		
		//实际支付金额
		//运费金额    目前看下单设置的为零 确认下设置值？？
		BigDecimal freightPrice=new BigDecimal(0);
		storeOrder.setFreightPrice(freightPrice);
		//邮费   确认下获取值逻辑设置值？？
		BigDecimal totalPostage=new BigDecimal(0);
		storeOrder.setTotalPostage(totalPostage);
		//邮费   确认下获取值逻辑设置值？？
		BigDecimal payPostage=new BigDecimal(0);
		storeOrder.setPayPostage(payPostage);
		
		Double totalAdd=ArithUtil.add(totalPrice.doubleValue(), totalPostage.doubleValue());
		totalAdd=ArithUtil.add(totalAdd,freightPrice.doubleValue());
		
		double totalSub=ArithUtil.add(deducteGold.doubleValue(),discountAmount.doubleValue());
		
		Double payPrice=ArithUtil.sub(totalAdd,totalSub);
		
		
		
		
		//防止实际支付 负数
		if(payPrice<=0){
			payPrice=0d;
		}
		storeOrder.setPayPrice(new BigDecimal(payPrice));  
		//如果实际付款为零 则订单直接完成状态 并且是已支付
		if(payPrice.intValue()==0){
			//支付状态 
			storeOrder.setPaid(PayConstants.PAY_STATE_1);
			//订单状态（-1 : 申请退款 -2 : 退货成功 0：待发货；1：待收货；2：已收货；3：待评价；-1：已退款）
			storeOrder.setStatus(OrderStatusConstants.ORDER_STATUS_2);
		}
		/**
		 * 计算使用或获得抵扣金
		 * 1.先判断是否拥有有效抵扣金(eb_system_store_ddf_bill)
		 *    a.如果存在:则使用抵扣金进行扣除,即使当前商品存在有效单单返规则也不再生成新的抵扣金返回,本订单获取抵扣金为零(下次再下单再返回)
		 *    b.如果不存在: 查询抵扣金配置表,如果配置表存在有效期内抵扣金规则且有商品参与抵扣金则此单返回抵扣金,同时设置获得抵扣金额(一期先不做返回逻辑)
		 * 2.本单是否单单返订单
		 *    确认逻辑:如果此订单使用了抵扣金或者此单有返回抵扣金均为单单返单;否则不是  
		 */
		Map<String,Object> ddfBillMap=new HashMap<String,Object>();
		ddfBillMap.put("storeId", storeId);
		ddfBillMap.put("userId", userId);
		List<SystemStoreDdfBill> storeDdfBillList=storeDdfBillService.getEffectiveStoreDdfBillList(ddfBillMap);
		if(storeDdfBillList!=null && !storeDdfBillList.isEmpty()){
			BigDecimal getDdfPrice=new BigDecimal(0);
			storeOrder.setGetDdfPrice(getDdfPrice);
			storeOrder.setIsDdf(1);
		}else{
			//二期 考虑实现上面b如果不存在逻辑
			BigDecimal ddfPrice=new BigDecimal(0);
			storeOrder.setGetDdfPrice(ddfPrice);
			storeOrder.setIsDdf(0);//是否单单返订单 0:否;1:是
		}
		storeOrderMapper.insert(storeOrder);
		Integer orderprimaryId=storeOrder.getId();
		
		/**
		 * 新增订单购物详情表(eb_store_order_cart_info)
		 */
		if(storeCartAddList!=null && !storeCartAddList.isEmpty()){
			/*List<StoreOrderCartInfo> storeOrderCartInfoList=new ArrayList<StoreOrderCartInfo>();
			for(StoreCart storeCart:storeCartAddList){
				Integer productId=storeCart.getProductId();
				StoreProduct storeProduct=storeProductService.queryByPrimaryId(productId);
				Integer factoryId=storeProduct.getFactoryId();
				
				StoreOrderCartInfo storeOrderCartInfo=new StoreOrderCartInfo();
				storeOrderCartInfo.setOid(orderprimaryId);
				storeOrderCartInfo.setCartId(storeCart.getId());
				storeOrderCartInfo.setProductId(productId);
				//购买东西的详细信息 待拼接 json串 TO DO  待处理待处理
				String cartInfo=null;
				storeOrderCartInfo.setCartInfo(cartInfo);
				String unique=StringUtils.uuid();
				storeOrderCartInfo.setUnique(unique);
				storeOrderCartInfo.setFactoryId(factoryId);
				storeOrderCartInfoList.add(storeOrderCartInfo);
			}*/
			List<StoreOrderCartInfo> storeOrderCartInfoList = setStoreOrderCartInfo(storeId, totalPrice,storeCartAddList,orderprimaryId);
			storeOrderCartInfoService.insertBatch(storeOrderCartInfoList);
		}
		
		/**
		 * 单单反抵扣金明细  此处不抵扣 支付成功了再进行抵扣
		 * 如果实际需要支付金额为零 则扣减抵扣金 否则 再支付成功时间 才扣减
		 */
		
		if(payPrice.intValue()==0){
			
			if(storeDdfBillList!=null && !storeDdfBillList.isEmpty()){
				
				Double currentUseTotalValue=0.00d;
				
				Double orderUse=deducteGold.doubleValue();
				
				for(SystemStoreDdfBill storeDdfBill:storeDdfBillList){
					Long billId=storeDdfBill.getId();
					String ddfBillOrderId=storeDdfBill.getOrderId();
					BigDecimal totalAmount=storeDdfBill.getTotalAmount();//发放总金额
					BigDecimal usedAmount=storeDdfBill.getUsedAmount();//已使用总金额
					BigDecimal balance=storeDdfBill.getBalance();//余额
					
					Integer currentDateTime=(int) (new Date().getTime()/1000);
						//前端传递 要是有抵扣金额 deducteGold
						Double balanceValue=balance.doubleValue();
						currentUseTotalValue=ArithUtil.add(currentUseTotalValue, balanceValue);
						//要是用大于余额则全部使用
						if(currentUseTotalValue<=orderUse){
							//根据id更新对应已使用额度和剩余总额
							SystemStoreDdfBill updateStoreDdfBill=new SystemStoreDdfBill();
							updateStoreDdfBill.setId(billId);
							updateStoreDdfBill.setUsedAmount(totalAmount);
							BigDecimal upbalance=new BigDecimal(0);
							updateStoreDdfBill.setBalance(upbalance);
							storeDdfBillService.update(updateStoreDdfBill);
							
							//记录单单反抵扣金交易明细(eb_system_store_ddf_trade)
							SystemStoreDdfTrade systemStoreDdfTrade=new SystemStoreDdfTrade();
							systemStoreDdfTrade.setStoreId(storeId);
							systemStoreDdfTrade.setUid(userId);
							systemStoreDdfTrade.setBillId(billId);
							systemStoreDdfTrade.setOrderId(ddfBillOrderId);
							systemStoreDdfTrade.setType((byte)2);
							BigDecimal number=new BigDecimal(balanceValue);//使用掉余额
							systemStoreDdfTrade.setNumber(number);
							systemStoreDdfTrade.setAddTime(currentDateTime);
							systemStoreDdfTradeService.save(systemStoreDdfTrade);
							orderUse=orderUse-currentUseTotalValue;
						}else{
							//根据id更新对应已使用额度和剩余总额
							SystemStoreDdfBill updateStoreDdfBill=new SystemStoreDdfBill();
							updateStoreDdfBill.setId(billId);
							
							
							double upUseAmountDouble=ArithUtil.add(orderUse, usedAmount.doubleValue());
							
							BigDecimal upUseAmount=new BigDecimal(upUseAmountDouble);
							updateStoreDdfBill.setUsedAmount(upUseAmount);
							
							
							double upBalanceDouble=ArithUtil.sub(totalAmount.doubleValue(), upUseAmount.doubleValue());
							BigDecimal upbalance=new BigDecimal(upBalanceDouble);
							updateStoreDdfBill.setBalance(upbalance);
							
							
							storeDdfBillService.update(updateStoreDdfBill);
							
							//记录单单反抵扣金交易明细(eb_system_store_ddf_trade)
							SystemStoreDdfTrade systemStoreDdfTrade=new SystemStoreDdfTrade();
							systemStoreDdfTrade.setStoreId(storeId);
							systemStoreDdfTrade.setUid(userId);
							systemStoreDdfTrade.setBillId(billId);
							systemStoreDdfTrade.setOrderId(ddfBillOrderId);
							systemStoreDdfTrade.setType((byte)2);
							BigDecimal number=new BigDecimal(orderUse);
							systemStoreDdfTrade.setNumber(number);
							systemStoreDdfTrade.setAddTime(currentDateTime);
							systemStoreDdfTradeService.save(systemStoreDdfTrade);
							break;
						}
				}
			}
			
		}
				
		/**
		 * 新增订单操作记录表
		 */
		List<StoreOrderStatus> orderStatusList=new ArrayList<StoreOrderStatus>();
		Integer currentTime=(int) (new Date().getTime()/1000);
		StoreOrderStatus createStoreOrderStatus=new StoreOrderStatus();
		createStoreOrderStatus.setOid(orderprimaryId);
		createStoreOrderStatus.setChangeType("cache_key_create_order");
		createStoreOrderStatus.setChangeMessage("订单生成");
		createStoreOrderStatus.setChangeTime(currentTime);
		orderStatusList.add(createStoreOrderStatus);
		storeOrderStatusService.insertBatch(orderStatusList);
		
		StoreOnlinePayOrderVo storeOnlinePayOrderVo=new StoreOnlinePayOrderVo();
		storeOnlinePayOrderVo.setOrderId(storeOrder.getOrderId());
		storeOnlinePayOrderVo.setPayPrice(storeOrder.getPayPrice());
		return storeOnlinePayOrderVo;
	}

	/**
	 * 获取订单编号
	 */
	@Override
	public StoreOrder getOrderByCode(String orderId) {
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("orderId", orderId);
		List<StoreOrder> list = storeOrderMapper.getList(map);
		if(list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	/***
	 * 到店支付，扫用户支付吗，更新订单状态
	 * 增加提现余额
	 * @param orderInfo
	 */
	@Override
	public void updatePayOrder(StoreOrder orderInfo) {
		
		
		Integer paidId=orderInfo.getPaid();
		//扣除抵扣金
        deductGold(orderInfo, paidId);
		
		StoreOrder o = new StoreOrder();
		o.setId(orderInfo.getId());
		o.setStatus(2);
		o.setPaid(1);
		super.update(o);
		
		
		/**保存余额*/
		SystemStoreBill target = new SystemStoreBill();
		target.setStoreId(orderInfo.getStoreId());
		target.setLinkId(orderInfo.getId() + "");
		target.setPm("1");
		target.setTitle("自定义");
		target.setCategory("now_money");
		target.setType("order_complete");
		BigDecimal incomePrice = orderInfo.getPayPrice().multiply(new BigDecimal(0.994)).setScale(2,BigDecimal.ROUND_HALF_UP);
		BigDecimal servicePrice = orderInfo.getPayPrice().subtract(incomePrice);
		target.setNumber(incomePrice);
		target.setServiceCharge(servicePrice);
		target.setMark("订单id:"+orderInfo.getId()+"（"+orderInfo.getOrderId()+"）支付成功，总价："+orderInfo.getTotalPrice()+"元，实际支付："+orderInfo.getPayPrice()+"元，利润："+servicePrice+"元，微信手续费："+incomePrice+"元");
		//获取最后一条门店流水记录
		SystemStoreBill billTemp = systemStoreBillService.getLastTimeInfo(orderInfo.getStoreId());
		BigDecimal totalPrice = incomePrice;
		if(billTemp != null) {
			totalPrice = totalPrice.add(billTemp.getBalance());
		}
		target.setBalance(totalPrice);
		target.setAddTime(DateUtil.getUTCTime(null).intValue());
		systemStoreBillService.save(target);
		
		/**支付*/
		SystemStore t = new SystemStore();
		t.setId(orderInfo.getStoreId());
		t.setAddAmount(incomePrice);
		systemStoreService.update(t);
		
		/**保存门店动态*/
		saveStoreReminder(orderInfo);
		
	}

	private void deductGold(StoreOrder orderInfo, Integer paidId) {
		//未支付情况下再使用抵扣金
		if(paidId!=null && paidId.equals(0)){
			Integer storeId=orderInfo.getStoreId();
			Integer userId=orderInfo.getUid();
			//当时订单使用的抵扣金总额
			BigDecimal usedDdfPrice=orderInfo.getUsedDdfPrice();
			Double orderUse=usedDdfPrice.doubleValue();
			
			
			//扣减抵扣
			Map<String,Object> ddfBillMap=new HashMap<String,Object>();
			ddfBillMap.put("storeId", storeId);
			ddfBillMap.put("userId", userId);
			List<SystemStoreDdfBill> storeDdfBillList=storeDdfBillService.getEffectiveStoreDdfBillList(ddfBillMap);
			
			/**
			 * 单单反抵扣金明细
			 * 
			 */
			if(storeDdfBillList!=null && !storeDdfBillList.isEmpty()){
				Double currentUseTotalValue=0.00d;
				for(SystemStoreDdfBill storeDdfBill:storeDdfBillList){
					Long billId=storeDdfBill.getId();
					String ddfBillOrderId=storeDdfBill.getOrderId();
					BigDecimal totalAmount=storeDdfBill.getTotalAmount();//发放总金额
					BigDecimal usedAmount=storeDdfBill.getUsedAmount();//已使用总金额
					BigDecimal balance=storeDdfBill.getBalance();//余额
					
					
					Integer currentDateTime=(int) (new Date().getTime()/1000);
					//防止 使用总额大于发放总额
					if(totalAmount.doubleValue()>usedAmount.doubleValue()){
						//前端传递 要是有抵扣金额 deducteGold
						Double balanceValue=balance.doubleValue();
						currentUseTotalValue=ArithUtil.add(currentUseTotalValue, balanceValue);
						//要是用大于余额则全部使用
						if(currentUseTotalValue<=orderUse){
							//根据id更新对应已使用额度和剩余总额
							SystemStoreDdfBill updateStoreDdfBill=new SystemStoreDdfBill();
							updateStoreDdfBill.setId(billId);
							updateStoreDdfBill.setUsedAmount(totalAmount);
							BigDecimal upbalance=new BigDecimal(0);
							updateStoreDdfBill.setBalance(upbalance);
							storeDdfBillService.update(updateStoreDdfBill);
							
							//记录单单反抵扣金交易明细(eb_system_store_ddf_trade)
							SystemStoreDdfTrade systemStoreDdfTrade=new SystemStoreDdfTrade();
							systemStoreDdfTrade.setStoreId(storeId);
							systemStoreDdfTrade.setUid(userId);
							systemStoreDdfTrade.setBillId(billId);
							systemStoreDdfTrade.setOrderId(ddfBillOrderId);
							systemStoreDdfTrade.setType((byte)2);
							BigDecimal number=new BigDecimal(balanceValue);//使用掉余额
							systemStoreDdfTrade.setNumber(number);
							systemStoreDdfTrade.setAddTime(currentDateTime);
							systemStoreDdfTradeService.save(systemStoreDdfTrade);
							orderUse=orderUse-currentUseTotalValue;
						}else{
							//根据id更新对应已使用额度和剩余总额
							SystemStoreDdfBill updateStoreDdfBill=new SystemStoreDdfBill();
							updateStoreDdfBill.setId(billId);
							
							BigDecimal upUseAmount=new BigDecimal(orderUse+usedAmount.doubleValue());
							updateStoreDdfBill.setUsedAmount(upUseAmount);
							
							BigDecimal upbalance=new BigDecimal(totalAmount.doubleValue()-upUseAmount.doubleValue());
							updateStoreDdfBill.setBalance(upbalance);
							storeDdfBillService.update(updateStoreDdfBill);
							
							//记录单单反抵扣金交易明细(eb_system_store_ddf_trade)
							SystemStoreDdfTrade systemStoreDdfTrade=new SystemStoreDdfTrade();
							systemStoreDdfTrade.setStoreId(storeId);
							systemStoreDdfTrade.setUid(userId);
							systemStoreDdfTrade.setBillId(billId);
							systemStoreDdfTrade.setOrderId(ddfBillOrderId);
							systemStoreDdfTrade.setType((byte)2);
							BigDecimal number=new BigDecimal(orderUse);
							systemStoreDdfTrade.setNumber(number);
							systemStoreDdfTrade.setAddTime(currentDateTime);
							systemStoreDdfTradeService.save(systemStoreDdfTrade);
							break;
						}
					}
				}
			}
		}
	}

	private void saveStoreReminder(StoreOrder orderInfo) {
		try{
			StoreReminder o = new StoreReminder();
			o.setReminderSn(StringUtils.getReminderSn());
			o.setReminderType("20");
			o.setStoreId(orderInfo.getStoreId());
			o.setStoreName(systemStoreService.queryById(orderInfo.getStoreId() + "").getName());
			o.setDataId(orderInfo.getId()+"");
			o.setTitle("订单支付");
			o.setMsg("订单"+orderInfo.getId()+"("+orderInfo.getOrderId()+")<i style=\"color: red;\">成功支付"+(orderInfo.getPayPrice().setScale(2, BigDecimal.ROUND_HALF_UP))+"元</i>");
			storeReminderService.save(o);
		} catch(Exception e) {
			logger.error("保存门店动态异常", e);
		}
		
	}

	@Override
	public Double countTotalPayPrice(Integer storeId, Integer isChannel) {
		Map<String,Object> queryMap=new HashMap<String,Object>();
		queryMap.put("storeId", storeId);
		queryMap.put("isChannel", isChannel);
		Double totalPayPrict=storeOrderMapper.countTotalPayPrice(queryMap);
		return totalPayPrict;
	}
}